#include "config.h"
#include "eeprom.h"

SystemConfig sysconfig;
// 加载配置
bool config_load() {
    SystemConfig *config = &sysconfig;
    
    // 从EEPROM读取配置
    if (!eeprom_read(CONFIG_EEPROM_ADDRESS, config, sizeof(SystemConfig))) {
        return false;
    }
    
    // 验证配置
    if (!config_validate(config)) {
        return false;
    }
    
    return true;
}

// 保存配置
bool config_save() 
{
    SystemConfig *config = &sysconfig;
    if (!config || !config_validate(config)) return false;
    
    // 计算校验和
    config->checksum = eeprom_calculate_checksum(config, sizeof(SystemConfig) - sizeof(config->checksum));

    // 写入EEPROM
    return eeprom_write(CONFIG_EEPROM_ADDRESS, config, sizeof(SystemConfig));
    // return true;
}

// 设置默认配置
void config_set_defaults() {
    SystemConfig *config = &sysconfig;
    
    memset(config, 0, sizeof(SystemConfig));

    config->current_threshold = DEFAULT_CURRENT_THRESHOLD;
    config->current_hysteresis = DEFAULT_CURRENT_HYSTERESIS;
    config->cooling_time_limit = DEFAULT_COOLING_TIME_LIMIT;
    config->preservation_temp = DEFAULT_PRESERVATION_TEMP;
    config->preservation_hysteresis = DEFAULT_PRESERVATION_HYSTERESIS;
    config->check_interval = DEFAULT_CHECK_INTERVAL;
    config->thawing_time = DEFAULT_THAWING_TIME;
    config->version = CONFIG_VERSION;
    
    // 计算校验和
    config->checksum = eeprom_calculate_checksum(config, sizeof(SystemConfig) - sizeof(config->checksum));
}

// 验证配置有效性
bool config_validate(const SystemConfig *config) {
    if (!config) return false;
    
    // 检查版本
    if (config->version != CONFIG_VERSION) return false;
    
    // 检查校验和
   uint16_t calculated = eeprom_calculate_checksum(config, sizeof(SystemConfig) - sizeof(config->checksum));
    if (calculated != config->checksum) return false;
    
    // 检查参数范围
    if (config->current_threshold <= 0 || 
        config->current_hysteresis <= 0 || config->current_hysteresis >= 1 ||
        config->cooling_time_limit <= 0 ||
        config->preservation_temp <= 0 ||
        config->preservation_hysteresis <= 0 ||
        config->check_interval <= 0 ||
        config->thawing_time <= 0) {
        return false;
    }
    
    return true;
}
    
void config_init(void) {
    // 加载配置
    if (!config_load()) {
        // 配置无效，设置默认值
        config_set_defaults();
        
        // 保存配置
        config_save();
    }
}
const SystemConfig *config_get()
{
    return &sysconfig;
}